<script setup lang="ts">
  import { ref, watch } from 'vue'
  import UpdateNetworkForm from './UpdateNetworkForm.vue'
  import { ElMessage } from 'element-plus'
  import { useRouter } from 'vue-router'

  const props = defineProps<{
    network: string
    networkId: string
    orderId: string
    modelValue: boolean
    address: {
      province: string
      city: string
      area: string
      town: string
    }
  }>()

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'update:modelValue', value: boolean)
  }>()

  const visible = ref(false)
  const router = useRouter()
  const updateNetworkFormRef = ref<InstanceType<typeof UpdateNetworkForm> | null>(null)

  const onSave = async () => {
    if (updateNetworkFormRef.value) {
      try {
        const res = await updateNetworkFormRef.value.save()
        ElMessage({
          type: res.success ? 'success' : 'error',
          message: res.message,
          duration: 5000,
          plain: true,
          showClose: true,
        })

        if (res.success) {
          visible.value = false
          emits('update')
          emits('update:modelValue', visible.value)
        }
      } catch (error) {
        // 切不可删除该注释，否则会引起eslint报错
        // 也不可删除catch块，否则会引起控制台报错
      }
    }
  }

  const onCancel = () => {
    if (updateNetworkFormRef.value) {
      updateNetworkFormRef.value.resetForm()
      visible.value = false
      emits('update:modelValue', false)
    }
  }

  const onAddNetowrk = () => {
    onCancel()
    router.push({ path: '/net/new' })
  }

  watch(
    () => props.modelValue,
    (value) => {
      visible.value = value
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <HDialog
      v-model="visible"
      title="改派网点"
      :loading="updateNetworkFormRef && updateNetworkFormRef.saveLoading"
      @close="onCancel"
    >
      <div class="update_network_modal_content">
        <div class="title">
          <i class="iconfont icon-warning"></i>
          <span class="text">改派后，该工单不再属于原网点</span>
        </div>
        <UpdateNetworkForm
          ref="updateNetworkFormRef"
          :network-id="props.networkId"
          :order-id="props.orderId"
          :address="props.address"
          :network="props.network"
          @add-network="onAddNetowrk"
        />
      </div>

      <!-- 按钮组 -->
      <template #footer>
        <HButton is-modal type="primary" @click="onSave">保存</HButton>
        <HButton is-modal @click="onCancel">取消</HButton>
      </template>
    </HDialog>
  </div>
</template>

<style scoped lang="scss">
  @import './UpdateNetwork.scss';
</style>
